<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Star, FolderOpened, Plus, Delete, Edit } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

interface Bookmark {
  id: string;
  title: string;
  url: string;
  icon?: string;
  folderId?: string;
}

interface BookmarkFolder {
  id: string;
  title: string;
  expanded?: boolean;
}

const bookmarks = ref<Bookmark[]>([]);
const folders = ref<BookmarkFolder[]>([]);
const showEditDialog = ref(false);
const editingBookmark = ref<Bookmark | null>(null);
const newBookmarkTitle = ref('');
const newBookmarkUrl = ref('');
const newBookmarkFolderId = ref('');
const contextMenuVisible = ref(false);
const contextMenuPosition = ref({ x: 0, y: 0 });
const contextMenuBookmark = ref<Bookmark | null>(null);

const emit = defineEmits<{
  (e: 'navigate', url: string): void;
}>();

/**
 * 加载书签
 */
async function loadBookmarks() {
  try {
    // 这里应该调用本地存储或数据库API加载书签
    // 目前使用模拟数据
    const defaultBookmarks: Bookmark[] = [
      { id: '1', title: 'Google', url: 'https://www.google.com', icon: 'https://www.google.com/favicon.ico' },
      { id: '2', title: 'Bing', url: 'https://www.bing.com', icon: 'https://www.bing.com/favicon.ico' },
      { id: '3', title: 'GitHub', url: 'https://github.com', icon: 'https://github.com/favicon.ico' },
    ];
    
    const defaultFolders: BookmarkFolder[] = [
      { id: 'folder1', title: '收藏夹' },
    ];
    
    bookmarks.value = defaultBookmarks;
    folders.value = defaultFolders;
  } catch (error) {
    console.error('加载书签失败:', error);
    ElMessage.error('加载书签失败');
  }
}

/**
 * 添加书签
 */
async function addBookmark(url: string, title: string, icon?: string, folderId?: string) {
  // 检查是否已存在相同URL的书签
  const existingBookmark = bookmarks.value.find(bookmark => bookmark.url === url);
  if (existingBookmark) {
    ElMessage.info('书签已存在');
    return false;
  }
  
  // 创建新书签
  const newBookmark: Bookmark = {
    id: Date.now().toString(),
    title,
    url,
    icon,
    folderId
  };
  
  // 添加到书签列表
  bookmarks.value.push(newBookmark);
  
  // 这里应该调用本地存储或数据库API保存书签
  // saveBookmarks();
  
  ElMessage.success('书签添加成功');
  return true;
}

/**
 * 删除书签
 */
function deleteBookmark(bookmarkId: string) {
  ElMessageBox.confirm('确定要删除这个书签吗?', '删除书签', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 从列表中删除
    bookmarks.value = bookmarks.value.filter(bookmark => bookmark.id !== bookmarkId);
    
    // 这里应该调用本地存储或数据库API删除书签
    // saveBookmarks();
    
    ElMessage({
      type: 'success',
      message: '书签已删除'
    });
  }).catch(() => {
    // 用户取消删除操作
  });
}

/**
 * 编辑书签
 */
function editBookmark(bookmark: Bookmark) {
  editingBookmark.value = { ...bookmark };
  newBookmarkTitle.value = bookmark.title;
  newBookmarkUrl.value = bookmark.url;
  newBookmarkFolderId.value = bookmark.folderId || '';
  showEditDialog.value = true;
}

/**
 * 保存编辑的书签
 */
function saveEditedBookmark() {
  if (!editingBookmark.value) return;
  
  // 验证输入
  if (!newBookmarkTitle.value.trim() || !newBookmarkUrl.value.trim()) {
    ElMessage.warning('请输入有效的标题和URL');
    return;
  }
  
  // 更新书签
  const index = bookmarks.value.findIndex(b => b.id === editingBookmark.value?.id);
  if (index !== -1) {
    bookmarks.value[index] = {
      ...bookmarks.value[index],
      title: newBookmarkTitle.value,
      url: newBookmarkUrl.value,
      folderId: newBookmarkFolderId.value || undefined
    };
    
    // 这里应该调用本地存储或数据库API更新书签
    // saveBookmarks();
    
    ElMessage.success('书签已更新');
    showEditDialog.value = false;
  }
}

/**
 * 显示右键菜单
 */
function showContextMenu(event: MouseEvent, bookmark: Bookmark) {
  event.preventDefault();
  contextMenuPosition.value = { x: event.clientX, y: event.clientY };
  contextMenuBookmark.value = bookmark;
  contextMenuVisible.value = true;
  
  // 点击其他地方关闭菜单
  document.addEventListener('click', closeContextMenu, { once: true });
}

/**
 * 关闭右键菜单
 */
function closeContextMenu() {
  contextMenuVisible.value = false;
}

/**
 * 处理书签点击
 */
function handleBookmarkClick(bookmark: Bookmark) {
  emit('navigate', bookmark.url);
}

defineExpose({
  addBookmark
});

onMounted(() => {
  loadBookmarks();
});
</script>

<template>
  <div class="bookmark-bar">
    <!-- 书签列表 -->
    <div class="bookmarks-container">
      <div 
        v-for="bookmark in bookmarks" 
        :key="bookmark.id"
        class="bookmark-item"
        @click="handleBookmarkClick(bookmark)"
        @contextmenu="showContextMenu($event, bookmark)"
      >
        <div class="bookmark-icon">
          <img v-if="bookmark.icon" :src="bookmark.icon" alt="icon" />
          <el-icon v-else><Star /></el-icon>
        </div>
        <div class="bookmark-title" :title="bookmark.title">
          {{ bookmark.title }}
        </div>
      </div>
    </div>
    
    <!-- 添加书签按钮 -->
    <div class="add-bookmark-button" @click="editBookmark({
      id: 'new',
      title: '',
      url: '',
    })">
      <el-icon><Plus /></el-icon>
    </div>
    
    <!-- 书签编辑对话框 -->
    <el-dialog
      v-model="showEditDialog"
      :title="editingBookmark?.id === 'new' ? '添加书签' : '编辑书签'"
      width="400px"
    >
      <el-form label-position="top">
        <el-form-item label="标题">
          <el-input v-model="newBookmarkTitle" placeholder="输入标题" />
        </el-form-item>
        <el-form-item label="URL">
          <el-input v-model="newBookmarkUrl" placeholder="输入URL" />
        </el-form-item>
        <el-form-item label="文件夹">
          <el-select v-model="newBookmarkFolderId" placeholder="选择文件夹" clearable>
            <el-option
              v-for="folder in folders"
              :key="folder.id"
              :label="folder.title"
              :value="folder.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="saveEditedBookmark">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 右键菜单 -->
    <div 
      v-if="contextMenuVisible" 
      class="context-menu"
      :style="{
        left: `${contextMenuPosition.x}px`,
        top: `${contextMenuPosition.y}px`
      }"
    >
      <div class="context-menu-item" @click="handleBookmarkClick(contextMenuBookmark!)">
        <el-icon><FolderOpened /></el-icon>
        <span>打开</span>
      </div>
      <div class="context-menu-item" @click="
        emit('navigate', contextMenuBookmark!.url);
        closeContextMenu();
      ">
        <el-icon><FolderOpened /></el-icon>
        <span>在新标签页中打开</span>
      </div>
      <div class="context-menu-divider"></div>
      <div class="context-menu-item" @click="
        editBookmark(contextMenuBookmark!);
        closeContextMenu();
      ">
        <el-icon><Edit /></el-icon>
        <span>编辑</span>
      </div>
      <div class="context-menu-item" @click="
        deleteBookmark(contextMenuBookmark!.id);
        closeContextMenu();
      ">
        <el-icon><Delete /></el-icon>
        <span>删除</span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.bookmark-bar {
  display: flex;
  align-items: center;
  height: 30px;
  padding: 0 8px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
  overflow-x: auto;
  overflow-y: hidden;
  position: relative;
}

html.dark .bookmark-bar {
  background-color: #292a2d;
  border-bottom-color: #3c4043;
}

.bookmarks-container {
  display: flex;
  align-items: center;
  overflow-x: auto;
  flex: 1;
}

.bookmark-item {
  display: flex;
  align-items: center;
  padding: 0 10px;
  height: 28px;
  margin-right: 4px;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
  transition: background-color 0.2s;
}

.bookmark-item:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

html.dark .bookmark-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.bookmark-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  margin-right: 6px;
}

.bookmark-icon img {
  width: 16px;
  height: 16px;
  object-fit: contain;
}

.bookmark-title {
  font-size: 12px;
  color: #202124;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
}

html.dark .bookmark-title {
  color: #e8eaed;
}

.add-bookmark-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 4px;
  cursor: pointer;
  flex-shrink: 0;
  transition: background-color 0.2s;
}

.add-bookmark-button:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

html.dark .add-bookmark-button:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.context-menu {
  position: fixed;
  z-index: 1000;
  background-color: white;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 4px 0;
  min-width: 180px;
}

html.dark .context-menu {
  background-color: #3c4043;
  border-color: rgba(255, 255, 255, 0.1);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.context-menu-item {
  display: flex;
  align-items: center;
  padding: 7px 10px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.context-menu-item:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

html.dark .context-menu-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.context-menu-item .el-icon {
  margin-right: 8px;
  color: #5f6368;
}

html.dark .context-menu-item .el-icon {
  color: #9aa0a6;
}

.context-menu-item span {
  font-size: 13px;
  color: #202124;
}

html.dark .context-menu-item span {
  color: #e8eaed;
}

.context-menu-divider {
  height: 1px;
  background-color: rgba(0, 0, 0, 0.1);
  margin: 4px 0;
}

html.dark .context-menu-divider {
  background-color: rgba(255, 255, 255, 0.1);
}
</style> 